package com.sky.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

@Data
@AllArgsConstructor
@Slf4j
public class MinioUtils {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    public String upload(byte[] bytes, String objectName) {
        try {
            //创建minio客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            //上传对象
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(new ByteArrayInputStream(bytes), bytes.length, -1)
                            .build()
            );
        }catch (Exception e) {
            log.error("上传文件失败：{}", e.getMessage());
            e.printStackTrace();
        }
        //返回访问路径
        StringBuilder url = new StringBuilder();
        url.append(endpoint)
                .append("/")
                .append(bucketName)
                .append("/")
                .append(objectName);
        log.info("文件上传成功，访问路径：{}", url.toString());
        return url.toString();
    }
}
